from flask_restful import Api
from werkzeug.exceptions import HTTPException


class UnifiedApi(Api):
    def handle_error(self, err):
        """统一错误处理"""
        code = err.code if isinstance(err, HTTPException) else 500
        messages = getattr(err, 'description', str(err))

        if isinstance(messages, dict):
            msg_list = [f"{k}: {v}" for k, v in messages.items()]
        else:
            msg_list = [messages] if isinstance(messages, str) else list(messages)

        return {"status": "fail", "msg": msg_list}, code


def _build_response(status, msg="", data=None, http_status=200, headers=None):
    """基础响应构造器"""
    return {
        "status": status,
        "msg": [msg],
        "data": data if data is not None else {}
    }, http_status, headers or {}


# 成功响应快捷方式
ResponseSuccess = lambda msg="操作成功", data=None, h=None: _build_response("success", msg, data, 200, h)
ResponseCreated = lambda msg="创建成功", data=None, h=None: _build_response("success", msg, data, 201, h)

# 错误响应快捷方式
ResponseBadRequest = lambda msg="参数错误", h=None: _build_response("fail", msg, None, 400, h)
ResponseUnauthorized = lambda msg="未授权", h=None: _build_response("fail", msg, None, 401, h)
ResponseNotFound = lambda msg="未找到", h=None: _build_response("fail", msg, None, 404, h)
ResponseConflict = lambda msg="资源冲突", h=None: _build_response("fail", msg, None, 409, h)